//
// Created by x on 2/4/24.
//

#include "msockettcp.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
/**
 *  异步读取数据
 */
void MSocketTCP::read() {
    this->async_read_some(asio::buffer(buffer,1024), [&](const error_code &error, std::size_t bytes_transferred)
    {
        this->readHandler(error, bytes_transferred);
    }
    );
}
/**
 *  异步读取数据
 * @param error  错误信息
 * @param bytes_transferred  读取的字节数
 */
void MSocketTCP::readHandler(const error_code &error, std::size_t bytes_transferred) {
    if (!error) {
        buffer[bytes_transferred] = 0;
        std::cout << "["<<this->remote_endpoint()<<"]len= " << bytes_transferred << "\t: " <<buffer<< std::endl;
        read();
    }
    else if (error == asio::error::eof)
    {
        // 连接已关闭
        // 调用错误处理函数
        std::cerr << "["<<this->remote_endpoint()<<"] close: " << error.message() << std::endl;
    }
    else {
        std::cerr << "["<<this->remote_endpoint()<<"] Error: " << error.message() << std::endl;
    }
}
